import {Avatar, type GetProp, Layout, Menu, type MenuProps, message} from "antd";
import {Content, Header} from "antd/es/layout/layout";
import {useUserState} from "../states/user.ts";
import {logout, type UserInfo} from "../request/user.ts";
import {NavLink, Outlet} from "react-router";
import Sider from "antd/es/layout/Sider";
import {calculateTheHeightIfFullWithPx} from "../utils/dom.ts";

export default function Home() {
    const {userInfo} = useUserState() as { userInfo: UserInfo };

    function handleLogout() {
        logout().then(res => {
            message.info(res.data.body ? "退出成功" : "退出失败").then(console.log);
        })

        if (sessionStorage.getItem('X-Authorization')) {
            sessionStorage.removeItem('X-Authorization')
        }
    }

    type MenuItem = GetProp<MenuProps, 'items'>[number];
    const menuItem: MenuItem[] = [
        {
            key: '1',
            label: <NavLink to='articleManagement'>文章管理</NavLink>
        }, {
            key: '2',
            label: <NavLink to='commentManagement'>评论管理</NavLink>
        }, {
            key: '3',
            label: <NavLink to='personalCenter'>个人中心</NavLink>
        }
    ]


    return <Layout>
        <Header style={{
            display: 'flex',
            justifyContent: 'right',
            alignItems: 'center',
            gap: 30
        }}>
            <div className='flex flex-row justify-center items-center gap-2'>
                <Avatar alt='用户不存在' src={userInfo.avatar}/>
                <div className='text-white capitalize'>{(userInfo.username)}</div>
            </div>
            <NavLink to='/login' onClick={handleLogout}>退出登录</NavLink>
        </Header>
        <Layout style={{height: calculateTheHeightIfFullWithPx()}}>
            <Sider theme='light'>
                <Menu
                    theme='light'
                    items={menuItem}
                    defaultOpenKeys={['1']}
                    defaultSelectedKeys={['1']}/>
            </Sider>
            <Content className='p-20 overflow-y-scroll '>
                <Outlet/>
            </Content>
        </Layout>
    </Layout>
}